package cn.itcast.xuesheng.web.servlet;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    private Random random=new Random();
    private Color getRandomColor() {
        //随机生成0-255之间整数
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        //参数：红，绿，蓝 (0-255)
        return new Color(red, green, blue);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int width=100;
        int height=50;
        BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics=bufferedImage.getGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0,0,width,height);
        graphics.setColor(Color.black);
        graphics.drawRect(0,0,width-1,height-1);
        String str="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM123456789";
        StringBuilder stringBuilder=new StringBuilder();
        for (int i=1;i<=4;i++) {
            int ran=random.nextInt(str.length());
            char ch=str.charAt(ran);
            stringBuilder.append(ch);
            graphics.setColor(getRandomColor());
            graphics.setFont(new Font(Font.DIALOG, Font.BOLD + Font.ITALIC, 19));
            graphics.drawString(ch+"",width/5*i,height/2);
        }
        String checkcode_session=stringBuilder.toString();
        request.getSession().setAttribute("checkcode_session",checkcode_session);

        for (int i=1;i<=8;i++){
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            graphics.setColor(getRandomColor());
            graphics.drawLine(x1,y1,x2,y2);

        }

        ImageIO.write(bufferedImage,"jpg",response.getOutputStream());

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
